<?php
class FriendModel extends Model {
	
	protected $partition = array ('field' => 'uid', 'type' => 'id', 'num' => '10' );
	
	const MAX_TABLE_NUM = 10;
	
	/**
	 * 
	 * 获取操作数据表
	 * @param $data
	 * 
	 * @example 
	 * $data['all'] = ture, 查询所有表;
	 * $data['uid'] = 'test', 查询用户名为'test'用户所在表;
	 * $data['idx'] = 2, 查询user_2	;
	 * $data['idx'] = 0, 查询user_0	;
	 */
	
	public function getDao($data = array()) {
		if ($data ['all']) {
			$table = $this->getTableAll ();
		} else if ($data ['uid']) {
			$table = $this->getTableByUname ( $data ['uid'] );
		} else {
			$table = $this->getTableById ( $data ['idx'] );
		}
		//$table = "user_2";
		return $this->table ( $table );
	}
	public function getTableAll() {
		// 当设置的分表字段不在查询条件或者数据中
		// 进行联合查询，必须设定 partition['num']
		$tableName = array ();
		for($i = 0; $i < $this->partition ['num']; $i ++)
			$tableName [] = 'SELECT * FROM ' . $this->getTableName () . '_' . $i;
		$table = '( ' . implode ( " UNION ", $tableName ) . ') AS ' . $this->name;
		return $table;
	}
	public function getTableByUname($uid) {
		$strkey = abs ( crc32 ( strval ( $uid ) ) );
		$idx = intval ( $strkey % FriendModel::MAX_TABLE_NUM );
		if ($idx > 0 && $idx < FriendModel::MAX_TABLE_NUM) {
			$table = "user_" . $idx;
		} else {
			$table = "user_0";
		}
		return $table;
	}
	
	public function getTableById($idx) {
		if ($idx > 0 && $idx < FriendModel::MAX_TABLE_NUM) {
			$table = "user_" . $idx;
		} else {
			$table = "user_0";
		}
		return $table;
	}
	
	
}